<?php declare(strict_types=1);
/**
 * Created by IntelliJ IDEA
 * Author: 张伯发
 * Date  : 2019/11/19
 * Time  : 11:51
 */

namespace App\Model\Dao;


use App\Model\Entity\Members;
use Swoft\Bean\Annotation\Mapping\Bean;

use Swoft\Db\Eloquent\Builder;
use Swoft\Db\Eloquent\Model;
use Swoft\Db\Exception\DbException;
use \ReflectionException;
use Swoft\Bean\Exception\ContainerException;
use Xiaoproject\Common\Base\BaseDao;


/**
 * Class MembersDao
 * @author 张伯发 2019/11/19 11:52
 * @Bean()
 */
class MembersDao extends BaseDao
{
    /**
     * @param string $username
     * @param string $password
     * @param string $nickname
     * @param string $headIcon
     * @return Members
     * @throws ReflectionException
     * @throws ContainerException
     * @throws DbException
     * @author 张伯发 2019/11/19 11:59
     */
    public function registerMember(string $username,
                                   string $password,
                                   string $nickname = '',
                                   string $headIcon = '') : ?Members
    {
        if (empty($username) || empty($password)) return null;

        $members = new Members();
        $members->setUsername($username);
        $members->setPassword(password_hash($password, PASSWORD_BCRYPT));
        $members->setNickname($nickname);
        $members->setHeadIcon($headIcon);
        $saved = $members->save();
        if ($saved) return $members;
        return null;
    }


    /**
     *
     * @param string $username
     * @param string $password
     * @return Members |object| Builder| Model
     * @throws DbException
     * @author 张伯发 2019/11/19 16:40
     */
    public function findMember(string $username, string $password): ?Members
    {
        if (empty($username) || empty($password)) return null;
        $result = Members::where(['username' => $username, 'password' => $password])->first();
        return $result;
    }

    /**
     * @param string $username
     * @return Members| object| Builder| Model
     * @throws DbException
     * @author 张伯发 2019/11/20 17:57
     */
    public function findMemberByUsername(string $username) : ?Members
    {
        if (empty($username)) return null;
        return Members::where(['username' => $username])->first();
    }
}
